package com.situ.yB2C.upfile.service.impl;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.situ.yB2C.upfile.service.UpfileService;

@Service
public class UpfileServiceImpl implements UpfileService {
	private static final Logger LOG = LoggerFactory.getLogger(UpfileServiceImpl.class );
	//Map<文件类别，文件写出的目录>
	private Map<Integer,String> fileKindMap = new HashMap<Integer,String>();
	
	public UpfileServiceImpl() {
		fileKindMap.put(1, "upfile/useravatar/");//用户头像目录
		fileKindMap.put(2, "upfile/product/");//商品的目录
	}
	
	@Override
	public String dofileUpload(MultipartFile partFile, Integer fileKind, String realPath) {
		//得到上传的文件的名称
		String fileName = partFile.getOriginalFilename();
		//写出文件的相同的路径（相对于 目录的跟的路径）
		StringBuilder filePath = new StringBuilder();
		filePath.append(fileKindMap.get(fileKind)).append(Calendar.getInstance().getTimeInMillis()).append(fileName.substring(fileName.lastIndexOf(".")));
		LOG.debug("相对路径=" + filePath);
		LOG.debug("写出文件的绝对路径="+ realPath+ filePath);
		File toFile = new File(realPath + filePath);
		//处理一下目录不存在的问题
		File parentFile = toFile.getParentFile();
		if(!parentFile.exists()) {
			parentFile.mkdirs();
		}
		try {
			partFile.transferTo(toFile);
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		
		return filePath.toString();
	}

}











